package com.kusiri.kframework.ui
{
	import com.kusiri.kframework.action.IKfAction;
	
	import flash.utils.describeType;
	import flash.utils.getDefinitionByName;
	
	/**
	 * This class defines what actions to take for a certain event.
	 * 
	 * Each property (not starting with an underscore) is the name of the event.
	 */
	public dynamic class KfUiEventActions implements IKfUiEventActions
	{

		public function raiseEvent(uiComponent : IKfUiComponent, event : IKfUiComponentEvent) : void
		{
			if ( ! this[event.__name] )
			{
				// no actions specified
				return;
			}
			
			var actions : Array = this[event.__name];
			for each ( var eventAction : KfUiEventAction in actions)
			{

				var clazz : Class = getDefinitionByName(eventAction.clazz) as Class;
				var action : IKfAction =  new clazz();
				
				// auto wire the action and event based on name if possible
				var actionClassInfo:XML = describeType(action);
	
	            for each (var v:XML in actionClassInfo..variable) 
	            {
	            	var attrname : String = v.@name;
	            	if (attrname.charAt()=='_') continue;
	            	if ( ! event[attrname] ) continue;
	            	try 
	            	{
	 					action[attrname] = event[attrname];
	            	} 
	            	catch ( e : TypeError)
	            	{
	            		// ignore if the class types are not compatible
	            	}
	            }
	            
	            for each (var a:XML in actionClassInfo..accessor) 
	            {
	            	var accessorname : String = a.@name;
	            	if (accessorname.charAt()=='_') continue;
	            	if ( ! event[accessorname] ) continue;
	            	try 
	            	{
	 					action[accessorname] = event[accessorname];
	            	} 
	            	catch ( e : TypeError)
	            	{
	            		// ignore if the class types are not compatible
	            	}
	            }
				
				// wire up the properties of the event to the properties of the action
				if (eventAction.propertyMap)
				{
					for ( var prop : String in eventAction.propertyMap)
					{
						action[prop] = eventAction.propertyMap[prop] ? event[ eventAction.propertyMap[prop] ] : null;
					}
				}
				
				// execute the action
				action.execute();
			}
		}
	}
}